<?php

  include_once('./queries/utils.inc.php');

  function countLostMachines($connection, $from_scalar, $from_unit, $to_scalar, $to_unit) {
    $sql = "SELECT count(*) " .
           "FROM machines_horizontal mc " . 
           "WHERE mc.lastreportedtime < (current_timestamp - " .
                                     get_interval($from_scalar, $from_unit) .
                                     ") ";
    if (isset($to_scalar)) {
       $sql = $sql . "AND mc.lastreportedtime >= " . 
                "(current_timestamp - " . 
                 get_interval($to_scalar, $to_unit) . 
                ") ";
    }
    
    //echo $sql;
    $result = get_scalar(get_recordset($connection, $sql));
    return $result;

  }    

  function machineClassAd_agg_query($groupFields, $aggFuncs, $connection) {
    $fldCount = 0;
    $sql = "SELECT ";
    foreach($groupFields as $group) {
      if ($fldCount>0) $sql = $sql . ", ";
      $sql = $sql . "mc.{$group}";
      $fldCount++;
    }
    //echo "SQL after first it is: {$sql}<br />";
    foreach($aggFuncs as $agg) {
      if ($fldCount>0) $sql = $sql . ", ";
      $sql = $sql . $agg["func"] . "(" . $agg["field"] . ")";
      $fldCount++;
    }
    //echo "SQL after second it is: {$sql}<br />";

    $sql = $sql . " FROM machines_horizontal mc ";

    $sql = $sql . " WHERE mc.lastreportedtime >= " . 
                     "(current_timestamp - " .
                       get_interval(MACHINE_CLASSAD_VALID_INTERVAL_SCALAR,
                                    MACHINE_CLASSAD_VALID_INTERVAL_UNIT) .
                     ") ";

    //this is for testing empty sets, what not
    //$sql = $sql . " AND mc.machine_id = 'aish.cs.wisc.edu' ";

    if (count($groupFields)>0) {
      $sql = $sql . " GROUP BY ";

      $fldCount = 0;
      foreach($groupFields as $group) {
        if ($fldCount>0) $sql = $sql . ", ";
        $sql = $sql . "mc.{$group}";
        $fldCount++;
      }
    }
    //echo $sql;
    $rcount = get_recordcount($connection, $sql);

    //$rs = new recordset();
    $groupFields[count($groupFields)]="machine count";
    //$rs->__construct($rcount, $groupFields, get_recordset($connection, $sql));
    $rs = new recordset($rcount, $groupFields, 
                        get_recordset($connection, $sql));

    return $rs;
  }
  
  //machines in pool gets the number of machines with a classad in the last x time period
  function machine_pool_count($connection) {

    $groupBy = array();
    $aggs = array();
    $aggs[0] = array();
    $aggs[0]["func"] = "count";
    $aggs[0]["field"] = "*";
    
    $rs = machineclassAd_agg_query($groupBy, $aggs, $connection);
    return get_scalar($rs->getData());
  }

  function single_machine_horizontal_query($connection, $index, $machineid) {
    $date = TS_FORMAT;
    $sql = "SELECT " .
            "mca.machine_id, " .
            "mca.opsys, " .
            "mca.arch, " .
            "mca.state, " .
            "mca.activity, " .
            "mca.globaljobid, " . 
            "mca.keyboardidle, " .
            "mca.consoleidle, " .
            "mca.loadavg, " .
            "mca.condorloadavg, " .
            "mca.totalloadavg, " .
            "mca.virtualmemory, " .
            "mca.memory, " .
            "mca.totalvirtualmemory, " . 
            "mca.cpubusytime, " .
            "mca.cpuisbusy, " .
            "mca.currentrank, " .
            "mca.clockmin, " .
            "mca.clockday, " .
            "to_char(mca.lastreportedtime, '{$date}'), " .
            "to_char(mca.enteredcurrentactivity, '{$date}'), " .
            "to_char(mca.enteredcurrentstate, '{$date}'), " .
            "mca.updatesequencenumber, " .
            "mca.updatestotal, " .
            "mca.updatessequenced, " .
            "mca.updateslost " .
           "FROM machines_horizontal mca " .
           "WHERE mca.machine_id='{$machineid}' ";

    //$result=get_recordset($connection, $sql);
    unset($_SESSION["{$index}"]);
    $_SESSION["{$index}"] = array();
    $_SESSION["{$index}"]["title"]="Latest information about {$machineid}.";
    $_SESSION["{$index}"]["message"]="Latest information about {$machineid}.";

    $fields=array();
    $fields[0]="machine_id";
    $fields[1]="opsys";
    $fields[2]="arch";
    $fields[3]="state";
    $fields[4]="activity";    
    $fields[5]="globaljobid";
    $fields[6]="keyboard idle";
    $fields[7]="console idle";
    $fields[8]="load average";
    $fields[9]="condor load average";
    $fields[10]="total load average";
    $fields[11]="virtual memory";
    $fields[12]="memory";
    $fields[13]="total virtual memory";
    $fields[14]="cpu busy time";
    $fields[15]="cpu is busy";
    $fields[16]="current rank";
    $fields[17]="clock min";
    $fields[18]="clock day";
    $fields[19]="last reported time";
    $fields[20]="entered current activity";
    $fields[21]="entered current state";
    $fields[22]="update sequence number";
    $fields[23]="updates total";
    $fields[24]="updates sequenced";
    $fields[25]="updates lost";

    $rs = new recordset(1, $fields, get_recordset($connection, $sql));
  	return $rs;
  }

  function single_machine_vertical_query($connection, $index, $machineid) {
    $date = TS_FORMAT;
    $sql = "SELECT m.attr, m.val, to_char(m.start_time, '{$date}') " .
           "FROM machines_vertical m " .
		"WHERE m.machine_id='{$machineid}' ";
    $rcount = get_recordcount($connection, $sql);

    unset($_SESSION["{$index}"]);    
    $_SESSION["{$index}"] = array();
    $_SESSION["{$index}"]["title"]="Latest information about {$machineid}.";
    $_SESSION["{$index}"]["message"]="Latest information about {$machineid}.";

    $fields=array();
    $fields[0]="Attribute";
    $fields[1]="Value";
    $fields[2]="Timestamp";

    $rs = new recordset($rcount, $fields, get_recordset($connection, $sql));
  	return $rs;
  }

  function machineList($connection, $index, $params, $before_scalar, 
                       $before_unit, $after_scalar, $after_unit, $pn) {
  	$sql = "SELECT mca.machine_id, " .
           get_parsed_gjid_sql() . 
	         "FROM machines_horizontal mca ";
        $where = null;
        if (isset($before_scalar)) $where = "mca.lastreportedtime < " . 
                                             "(current_timestamp - " . 
                                             get_interval($before_scalar,
                                                          $before_unit) . ") ";
        if (isset($after_scalar)) {
          if (isset($before_scalar)) $where = $where . "AND ";
          $where = $where . "mca.lastreportedtime >= " . 
                             "(current_timestamp - " . 
                             get_interval($after_scalar, $after_unit) . ") ";
        }
        //echo "{$sql}";
	if(isset($params)) {
            //echo "in here";
	    //var_dump($param);
	    foreach($params as $field => $value) {
		$where = $where . " AND mca.{$field}='{$value}'"; 
		//echo $where;

	    }
	}
        if (isset($where)) $where = "WHERE " . $where;
        $sql = $sql . $where;
        $sql = $sql . " ORDER BY mca.machine_id";
        //echo $sql;
        $rcount = get_recordcount($connection, $sql);
        $sql = do_pagination_rewriting($pn, $rcount, $sql);


			//echo "{$sql}";
        unset($_SESSION["{$index}"]);    
        $_SESSION["{$index}"] = array();
   	    $_SESSION["{$index}"]["params"] = $params;
  
        $_SESSION["{$index}"]["before_scalar"] = $before_scalar;
        $_SESSION["{$index}"]["before_unit"] = $before_unit;
        $_SESSION["{$index}"]["after_scalar"] = $after_scalar;
        $_SESSION["{$index}"]["after_unit"] = $after_unit;

        $_SESSION["{$index}"]["title"]="Parameterized machine list.";
        $_SESSION["{$index}"]["message"]="Parameterized machine list.";

        $fields=array();
        $fields[0]="Machine Id";
        $fields[1]="schedd";
        $fields[2]="cid";
        $fields[3]="pid";

        $rs = new recordset($rcount, $fields, 
                            get_recordset($connection, $sql));
        return $rs;
  }

?>
